package com.lingx.web.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class ExitServer  implements Runnable {
    
    private final static Logger logger = LoggerFactory.getLogger(ApiServer.class);
    
    /**
     * 监听端口号
     */
    private int port = 0;
  
    
    public ExitServer(int port) {
        this.port = port;
    }
    
    /**
     * 启动服务
     * @throws InterruptedException 
     */
    public void startup() throws InterruptedException {
        
        // BossGroup处理nio的Accept事件（TCP连接）
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        // Worker处理nio的Read和Write事件（通道的I/O事件）
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        
        try {
            // handler在初始化时就会执行，而childHandler会在客户端成功connect后才执行。
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 128)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)       
            .childHandler(new ExitInitializer());
            
            ChannelFuture f = bootstrap.bind(port).sync();
            logger.info("The netty rest server is now ready to accept requests on port {}", this.port); 
            f.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

	@Override
	public void run() {
		try {
			startup();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
